﻿using System.Web.WebPages;
using WebMatrix.WebData;


namespace Account
{
    /// <summary>
    /// Summary description for ChangePassword
    /// </summary>
    public static class ChangePassword
    {
        public class Model
        {
            public string CurrentPassword { get; set; }
            public string NewPassword { get; set; }
            public string ConfirmPassword { get; set; }
        }

        public class Error
        {
            public ErrorMessage CurrentPassword { get; set; }
            public ErrorMessage NewPassword { get; set; }
            public ErrorMessage ConfirmPassword { get; set; }
            public ErrorMessage Provider { get; set; }

            public Error()
            {
                CurrentPassword = ErrorMessage.Nil;
                NewPassword = ErrorMessage.Nil;
                ConfirmPassword = ErrorMessage.Nil;
                Provider = ErrorMessage.Nil;
            }
        }

        public static void Init(WebPageBase web)
        {
            Model model = web.Page.Model = new Model();
            Error error = web.Page.Errors = new Error();

            web.Page.Success = false;
            
            model.CurrentPassword = web.Request["currentPassword"];
            model.NewPassword = web.Request["newPassword"];
            model.ConfirmPassword = web.Request["confirmPassword"];

            if (web.IsPost)
            {
                if (model.CurrentPassword.IsEmpty())
                {
                    error.CurrentPassword = web.Error("Please enter your current password.");
                }
                if (model.NewPassword.IsEmpty())
                {
                    error.NewPassword = web.Error("Please enter a new password.");
                }
                if (model.ConfirmPassword.IsEmpty())
                {
                    error.ConfirmPassword = web.Error("Please confirm your new password.");
                }
                if (model.ConfirmPassword != model.NewPassword)
                {
                    error.ConfirmPassword = web.Error("The password confirmation does not match the new password.");
                }

                if (web.Page.IsValid)
                {
                    if (WebSecurity.ChangePassword(WebSecurity.CurrentUserName, model.CurrentPassword, model.NewPassword))
                    {
                        web.Page.Success = true;
                        
                    }
                    else
                    {
                        error.Provider = web.Error("An error occurred when attempting to change the password. Please contact the site owner.");
                    }
                }
            }
        }
    }
}